package command

import (
	"errors"
	"github.com/gin-gonic/gin"
	"ssdevice/common/dto"
	"ssdevice/common/utils"
	"ssdevice/internal/rule/model"
	"strings"
	"time"
)

type RuleInsertReq struct {
	Name      string `json:"name" vd:"len($)>0"`
	Desc      string `json:"desc"`
	DevSn     string `json:"devSn"`
	ProductId string `json:"productId"`
	dto.UserInfo
}

func (r *RuleInsertReq) Generate(ruleModel *model.Rule, c *gin.Context) error {
	ruleModel.Id = utils.SimpleUUID()
	ruleModel.Name = strings.TrimSpace(r.Name)
	ruleModel.ProductId = strings.TrimSpace(r.ProductId)
	ruleModel.DevSn = strings.TrimSpace(r.DevSn)
	ruleModel.Status = model.RuleDisable
	ruleModel.Desc = strings.TrimSpace(r.Desc)

	r.LoadUser(c)
	ruleModel.Creator = r.UserId
	ruleModel.AgencyId = r.AgencyId

	now := dto.LocalTime(time.Now())
	ruleModel.CreateTime = now
	ruleModel.UpdateTime = now

	return nil
}

type RuleOperationReq struct {
	Id string `json:"id" vd:"len($)>0"`
	dto.UserInfo
}

type RuleUpdateReq struct {
	Id        string `json:"id"`
	Name      string `json:"name"`
	Desc      string `json:"desc"`
	ProductId string `json:"productId"`
	DevSn     string `json:"devSn" `
	dto.UserInfo
}

func (r *RuleUpdateReq) Generate(updates map[string]interface{}) error {
	if r.ProductId == "" && r.DevSn == "" {
		return errors.New("设备或产品不能同时为空")
	}

	if r.ProductId != "" && r.DevSn != "" {
		return errors.New("设备或产品不能同时设置")
	}

	updates["name"] = strings.TrimSpace(r.Name)
	updates["desc"] = strings.TrimSpace(r.Desc)
	updates["product_id"] = strings.TrimSpace(r.ProductId)
	updates["dev_sn"] = strings.TrimSpace(r.DevSn)
	now := dto.LocalTime(time.Now())
	updates["update_time"] = now

	return nil
}
